<template>
    <div>
        <div>
            <el-card>
                <el-form class="searchForm" size="mini" label-width="100px">
                    <el-form-item label="用户名称">
                        <el-input
                                style="width: 200px"
                                v-model="searchData.name"
                                placeholder="请输入用户名称"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="创建时间">
                        <el-date-picker
                                v-model="times"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                        >
                        </el-date-picker>
                    </el-form-item>

                    <div class="searchBtn">
                        <el-button type="primary" size="small" @click="keywordSearch"><i class="el-icon-search"></i> 搜索</el-button>
                        <el-button type="info" size="small" @click="clean"> <i class="el-icon-delete"></i> 清空</el-button>
                    </div>
                </el-form>
                <el-button class="btn" type="primary" size="small" @click="addDialogVisible=true"><i class="el-icon-plus"></i> 新增用户</el-button>
                <el-button class="btn" type="primary" size="small" @click="exportData"><i class="el-icon-download"></i> 用户信息excel导出</el-button>
                <el-button class="btn" type="primary" size="small" @click="importDialogVisible=true"><i class="el-icon-upload2"></i> 用户信息excel导入</el-button>
                <div>
                    <el-table
                            :data="userData"
                            height="450"
                            border
                            style="width: 100%"
                            :cell-style="{ 'text-align': 'center' }"
                            :header-cell-style="{ 'text-align': 'center' }"
                    >
                        <el-table-column type="index" label="编号" width="50"></el-table-column>
                        <el-table-column prop="username" label="用户名" ></el-table-column>
                        <el-table-column prop="name" label="用户昵称" ></el-table-column>
                        <el-table-column prop="phone" label="手机号" ></el-table-column>
                        <el-table-column prop="enableFlag" label="状态" width="100">
                            <template slot-scope="scope">
                                <el-tag>{{scope.row.enableFlag == '0' ? '正常' : '禁用'}}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="角色" width="400">
                            <template slot-scope="scope">
                                <el-tag  v-for="role in scope.row.roles"
                                           :key="role.id">
                                    {{ role.roleName }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="createTime" label="创建时间" width="220"></el-table-column>
                        <el-table-column label="操作" width="160">
                            <template slot-scope="scope">
                                <el-link type="primary" class="btn" icon="el-icon-edit" @click="editUserOpen(scope.row)"
                                >编辑
                                </el-link
                                >
                                <el-link type="danger" class="btn" icon="el-icon-delete" @click="removeUser(scope.row)"
                                >删除
                                </el-link
                                >
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-pagination
                            :total="pagingData.total"
                            background
                            layout="total,sizes, prev, pager, next"
                            :page-size="pagingData.size"
                            :page-sizes="[1, 5, 10, 20, 30, 50]"
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="pagingData.current"
                    ></el-pagination>

                        <el-dialog title="添加用户" :before-close="handleClose" :visible.sync="addDialogVisible" width="50%">
                            <el-form :model="userForm" label-position="left" label-width="100px" size="small">
                                <el-form-item label="用户名">
                                    <el-input v-model="userForm.username"></el-input>
                                </el-form-item>
                                <el-form-item label="用户昵称">
                                    <el-input v-model="userForm.name"></el-input>
                                </el-form-item>
                                <el-form-item label="密码">
                                    <el-input v-model="userForm.password"></el-input>
                                </el-form-item>
                                <el-form-item label="角色">
                                    <el-select v-model="userForm.roleIds" multiple placeholder="请选择">
                                        <el-option
                                                v-for="item in roleOptions"
                                                :key="item.id"
                                                :label="item.roleName"
                                                :value="item.id">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="手机号">
                                    <el-input v-model="userForm.phone"></el-input>
                                </el-form-item>
                            </el-form>
                            <span slot="footer" class="dialog-footer">
                                <el-button size="mini" @click="addDialogVisible = false,init()">取 消</el-button>
                                <el-button size="mini" type="primary" @click="addUser">确 定</el-button>
                            </span>
                        </el-dialog>

                    <el-dialog title="编辑用户" :before-close="handleClose" :visible.sync="editDialogVisible" width="50%">
                        <el-form :model="userForm" label-position="left" label-width="100px" size="small">
                            <el-form-item label="用户昵称">
                                <el-input v-model="userForm.name"></el-input>
                            </el-form-item>
                            <el-form-item label="用户名">
                                <el-input v-model="userForm.username"></el-input>
                            </el-form-item>
                            <el-form-item label="密码">
                                <el-input v-model="userForm.password"></el-input>
                            </el-form-item>
                            <el-form-item label="角色">
                                <el-select v-model="userForm.roleIds" multiple placeholder="请选择">
                                    <el-option
                                            v-for="item in roleOptions"
                                            :key="item.id"
                                            :label="item.roleName"
                                            :value="item.id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="手机号">
                                <el-input v-model="userForm.phone"></el-input>
                            </el-form-item>
                            <el-form-item label="状态">
                                <el-radio-group v-model="userForm.enableFlag">
                                    <el-radio label="0" value="0" border>正常</el-radio>
                                    <el-radio label="1" value="1" border>禁用</el-radio>
                                </el-radio-group>
                            </el-form-item>

                        </el-form>
                        <span slot="footer" class="dialog-footer">
							<el-button size="mini" @click="editDialogVisible = false,init()">取 消</el-button>
							<el-button size="mini" type="primary" @click="editUser">确 定</el-button>
						</span>
                    </el-dialog>
                    <el-dialog title="用户信息excel导入" :before-close="handleClose" :visible.sync="importDialogVisible" width="50%">
                        <el-upload
                                class="upload-demo"
                                drag
                                name="file"
                                :action="fileUploadUrl"
                                :on-success="importSuccess"
                                multiple>
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                            <div class="el-upload__tip" slot="tip">只能上传excel文件，且不超过500kb</div>
                        </el-upload>
                    </el-dialog>
                </div>
            </el-card>
        </div>
    </div>
</template>

<script>
    import {registerUser, findUserPage, deleteUser, updateUser, exportData} from "../../../api/admin/permissions/user"
    import moment from "moment"
    import {findAllRole} from "../../../api/admin/permissions/role";
    import * as settings from "../../../config/settings";

    export default {
        name: "user",
        data() {
            return {

                times: '',
                pagingData: {
                    current: 1,
                    size: 20,
                    total: 0
                },
                searchData: {
                    name: '',
                    startDate: '',
                    endDate: '',

                },
                roleOptions: [],
                userData: [],
                importDialogVisible:false,
                addDialogVisible: false,
                editDialogVisible: false,
                fileUploadUrl: '',
                fileList: [],
                userForm: {
                    id: "",
                    username: "admin1",
                    password: "111111",
                    phone: "",
                    name: "",
                    userFace: "",
                    enableFlag: "",
                    roleIds: []
                },
            }
        },
        created() {
            this.init();
            this.fileUploadUrl = settings.env == 'prod' ? settings.baseUrl.production : settings.baseUrl.development + "/admin/demo-user/importData";

            findAllRole({}).then(res => {
                this.roleOptions = res.data.data.records;
            })
        },
        methods: {
            /*
                关键词搜索
            */
            keywordSearch() {
                if (this.times.length > 0) {
                    this.searchData.startDate = moment(this.times[0]).format('YYYY-MM-DD mm:ss');
                    this.searchData.endDate = moment(this.times[1]).format('YYYY-MM-DD mm:ss');
                }

                let search = {
                    ...this.searchData,
                    // total: this.pagingData.total,
                    size: this.pagingData.size,
                    current: this.pagingData.current,
                }
                findUserPage(search).then((res) => {
                    this.pagingData.total = res.data.data.total
                    this.pagingData.size = res.data.data.size
                    this.pagingData.current = res.data.data.current
                    this.userData = res.data.data.records

                })
            },

            /**
             * 初始化/更新
             */
            init() {
                let search = {
                    ...this.searchData,
                    // total: this.pagingData.total,
                    size: this.pagingData.size,
                    current: this.pagingData.current,
                }
                findUserPage(search).then((res) => {
                    this.pagingData.total = res.data.data.total
                    this.pagingData.size = res.data.data.size
                    this.pagingData.current = res.data.data.current
                    this.userData = res.data.data.records

                })
            },
            /**
             * 创建用户
             */
            addUser() {
                registerUser(this.userForm).then(res => {
                    if (res.data.code == 200) {
                        this.$message.success('添加用户成功')
                        this.addDialogVisible = false;
                        this.init()
                    } else {
                        this.$message.error('添加用户失败')
                        this.addDialogVisible = false;
                    }

                })
                this.userForm = {};
            },
            /**
             *打开编辑表单
             */
            editUserOpen(row) {
                this.editDialogVisible = true;
                this.userForm = row;
                let roleIdList = []
                for (let i = 0; i < row.roles.length; i++) {
                    roleIdList.push(row.roles[i].id)
                }
                this.userForm.roleIds = roleIdList;
            },
            /**
             *修改用户
             */
            editUser() {
                updateUser(this.userForm).then(res => {
                    if (res.data.code == '200') {
                        this.editDialogVisible = false;
                        this.$message.success('修改用户成功')
                        this.init()
                    } else {
                        this.editDialogVisible = false;
                        this.$message.success('修改用户失败')
                    }

                })
            },
            /**
             * 删除用户
             */
            removeUser(row) {
                this.$confirm('确定要删除该用户？', '警告', {
                    distinguishCancelAndClose: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消'
                }).then(() => {
                    deleteUser(row.id).then(res => {
                        if (res.data.code == '200') {
                            this.$message.success('删除用户成功')
                            this.init()
                            return
                        }
                        this.$message.success('删除用户失败')
                        return
                    })
                }).catch(action => {

                })
            },
            /**
             * 所有用户数据excel导出
             */
            exportData() {
                const settings = require('../../../config/settings');
                window.location.href = settings.env == 'prod' ? settings.baseUrl.production : settings.baseUrl.development + "/admin/demo-user/exportData";
            },
            importSuccess(){
                this.importDialogVisible=false;
                this.init();
            },
            // 页码切换
            handleSizeChange(val) {
                this.pagingData.size = val
                this.init()
            },
            // 当前页切换
            handleCurrentChange(val) {
                this.pagingData.current = val
                this.init()
            },
            /**
             * 所有用户数据excel导出
             */
            exportData() {
                const settings = require("../../../config/settings")
                window.location.href =
                    settings.env == "prod"
                        ? settings.baseUrl.production
                        : settings.baseUrl.development + "/admin/demo-user/exportData"
            },
            /**
             * 关闭编辑表单框
             */
            handleClose(done) {
                this.init();
                done();
            },
            /**
             * 重置搜索框
             */
            clean() {
                this.searchData = {};
                this.times = []
            }
        },
    }
</script>

<style lang="scss" scoped>
    @import "~@/style/admin/permissions/user.scss";
</style>
